package com.neusoft.EYSystem.controller;

import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.dao.MealitemDAO;
import com.neusoft.EYSystem.dao.UserOfClientDAO;
import com.neusoft.EYSystem.po.Client;
import com.neusoft.EYSystem.po.Mealitem;
import com.neusoft.EYSystem.po.ResponseBean;
import com.neusoft.EYSystem.po.UserOfClient;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private UserOfClientDAO userOfClientDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Autowired
    private MealitemDAO mealItemDAO;

    @PostMapping("/upload")
    public ResponseBean<Map<String, Object>> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("ucId") Integer ucId,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 拼接用户专属目录
            UserOfClient userOfClient = userOfClientDAO.selectById(ucId);
            Integer clientId = userOfClient.getClientId();
            Client client = clientDAO.selectById(clientId);
            String username = client.getClientId() + "-" + client.getName(); // 使用客户名作为目录名
            String uploadDir = "D:/DESKTOP/upload/" + username + "/";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs(); // 自动创建目录

            // 2. 拼接新文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = username + "_" + System.currentTimeMillis() + suffix;

            // 3. 保存文件
            File dest = new File(uploadDir + newFileName);
            file.transferTo(dest);

            // 4. 拼接访问 URL（静态资源访问请看后面说明）
            String fileUrl = request.getScheme() + "://" +
                    request.getServerName() + ":" +
                    request.getServerPort() +
                    "/upload/" + username + "/" + newFileName;
            userOfClient.setAvatarUrl(fileUrl); // 更新用户的文件URL
            userOfClientDAO.updateById(userOfClient);
            result.put("isOK", true);
            result.put("url", fileUrl);
        } catch (Exception e) {
            result.put("isOK", false);
            result.put("msg", "上传失败：" + e.getMessage());
            return new ResponseBean<>(500, "上传失败", result);
        }
        return new ResponseBean<>(200, "上传成功", result);
    }

    @PostMapping("/uploadMealP")
    public ResponseBean<Map<String, Object>> uploadMealItemPicture(
            @RequestParam("file") MultipartFile file,
            @RequestParam("mealItemId") Integer mealItemId,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            Mealitem mealItem = mealItemDAO.selectById(mealItemId);
            if (mealItem == null) {
                result.put("isOK", false);
                result.put("msg", "菜品不存在");
                return new ResponseBean<>(404, "菜品不存在", result);
            }
            String mealDirName = mealItem.getMealitemId() + "-" + mealItem.getName();
            String uploadDir = "D:/DESKTOP/upload/mealitem/" + mealDirName + "/";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs();

            // 2. 拼接新文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = mealDirName + "_" + System.currentTimeMillis() + suffix;

            // 3. 保存文件
            File dest = new File(uploadDir + newFileName);
            file.transferTo(dest);

            // 4. 拼接访问URL
            String fileUrl = request.getScheme() + "://" +
                    request.getServerName() + ":" +
                    request.getServerPort() +
                    "/upload/mealitem/" + mealDirName + "/" + newFileName;

            // 5. 更新菜品图片URL
            mealItem.setImgUrl(fileUrl);
            mealItemDAO.updateById(mealItem);

            result.put("isOK", true);
            result.put("url", fileUrl);
        } catch (Exception e) {
            result.put("isOK", false);
            result.put("msg", "上传失败：" + e.getMessage());
            return new ResponseBean<>(500, "上传失败", result);
        }
        return new ResponseBean<>(200, "上传成功", result);
    }
}
